package com.nanbei.smsService.controller;

import com.nanbei.commonUntil.R;
import com.nanbei.commonUntil.RandomUtil;
import com.nanbei.servicebase.exceptionHandler.GuliException;
import com.nanbei.smsService.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/smsService/sms")
@CrossOrigin
public class SmsController {

    @Autowired
    private SmsService smsService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/sendEmail/{emailId}")
    public R sendSms(@PathVariable String emailId){

        if (StringUtils.isEmpty(emailId)){
            throw new GuliException(20001,"邮箱不能为空");
        }

        //先生成一个6位数的验证码
        String sixBitRandom = RandomUtil.getSixBitRandom();

        try {
            smsService.sendSms(sixBitRandom,emailId);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw  new GuliException(20001,"发送邮箱验证码失败");
        }

        redisTemplate.opsForValue().set(emailId,sixBitRandom,10, TimeUnit.MINUTES);

        return R.ok();
    }

}
